<template>
  <div class="work-detail-container">
    <el-row v-if="template" justify="center">
      <el-col :span="8" class="cover-img">
        <img id="cover-img" :src="template.coverImg" />
      </el-col>
      <el-col :span="8">
        <h2>{{ template.title }}</h2>
        <p style="margin-top: 10px">{{ template.desc }}</p>
        <div class="author">
          <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
          该模版由
          <span class="name">{{ template.author }}</span>
          创作
        </div>
        <div class="bar-code-area">
          <span>扫一扫，手机预览</span>
          <canvas id="barcode-container"></canvas>
        </div>
        <div class="use-button">
          <el-button type="primary" size="large" @click="onCopy">使用模版</el-button>
          <el-button style="margin-left: 12px" size="large" @click="download">下载图片海报</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { useTemplatesStore } from '@/stores/templates'
import { useEditorStore } from '@/stores/editor'
import { generateQRCode, downloadImage } from '@/utils/utils'
import { baseH5URL } from '@/service/request'

const router = useRouter()
const editor = useEditorStore()
const templates = useTemplatesStore()
const route = useRoute()
const currentId = route.params.id as string
const template = computed(() => templates.getTemplateById(parseInt(currentId)))
const channelURL = computed(() => `${baseH5URL}/p/${template.value.id}-${template.value.uuid}`)

onMounted(async () => {
  await templates.fetchTemplate(currentId)
  await nextTick()
  await generateQRCode('barcode-container', channelURL.value, 150)
})

const onCopy = async () => {
  const workData = await editor.copyWork(parseInt(currentId))
  router.push(`/editor/${workData.id}`)
}

const download = () => {
  downloadImage(template.value.coverImg)
}
</script>
<style lang="scss" scoped>
.work-detail-container {
  margin-top: 50px;
  .cover-img {
    margin-right: 30px;
    img {
      width: 100%;
    }
  }
  .author {
    display: flex;
    align-items: center;
    margin-top: 16px;
    .name {
      font-weight: 500;
      margin: 0 6px;
    }
  }
  .el-avatar {
    margin-right: 10px;
  }

  .bar-code-area {
    margin: 20px 0;
  }

  .use-button {
    margin: 30px 0;
  }
}

#barcode-container {
  display: block;
  border: 2px dotted #efefef;
  margin-top: 10px;
}
</style>
